package com.utils;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class PlayUtil {
	
	private static Logger LOG = LoggerFactory.getLogger(PlayUtil.class);
	
	public static volatile boolean isPlaying = true;
	
	private static boolean enabledIntercepted = false;
	
	private static SourceDataLine line;
	
	public static void setIntercepted(boolean flag) {
		enabledIntercepted = flag;
	}
	/**
	 * 播放文件
	 * @param filePath
	 */
	@SuppressWarnings("static-access")
	public static void play(String filePath) {
		AudioInputStream ais = null;
		try {
			isPlaying = true;
			ais = AudioSystem.getAudioInputStream(new File(filePath));// 获得音频输入流
			AudioFormat baseFormat = ais.getFormat();// 指定声音流中特定数据安排
			LOG.info("baseFormat=" + baseFormat);
			DataLine.Info info = new DataLine.Info(SourceDataLine.class, baseFormat);
			LOG.info("info=" + info);
			line = (SourceDataLine) AudioSystem.getLine(info);
			// 从混频器获得源数据行
			line.open(baseFormat);// 打开具有指定格式的行，这样可使行获得所有所需的系统资源并变得可操作。
			line.start();// 允许数据行执行数据 I/O
			int BUFFER_SIZE = 6400;
			int intBytes = 0;
			byte[] audioData = new byte[BUFFER_SIZE];
			while (!enabledIntercepted && intBytes != -1) {
				intBytes = ais.read(audioData, 0, BUFFER_SIZE);// 从音频流读取指定的最大数量的数据字节，并将其放入给定的字节数组中。
				if (intBytes >= 0) {
					line.write(audioData, 0, intBytes);// 通过此源数据行将音频数据写入混频器。
				}
			}
		} catch (Exception e) {
			LOG.error("播放错误",e);
		} finally {
			if(ais != null) {
				try {
					Thread.currentThread().sleep(2000);
					line.flush();
					line.close();
					ais.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			isPlaying = false;
		}
	}
	/**
	 * 停止播放
	 */
	public static void stop() {
		if(enabledIntercepted) {
			//line.stop();
			try {
				enabledIntercepted = true;
				line.close();
				isPlaying = false;
			} catch (Exception e) {
				LOG.error("停止失败！",e);
			}finally {
				enabledIntercepted = false;
			}
		}else {
			LOG.warn("当前播放不可中断！请设置  setIntercepted(boolean flag) ");
		}
	}
}
